package cn.hallele.bbts.core.common.utils;

import cn.hutool.extra.servlet.JakartaServletUtil;
import cn.hutool.http.Header;
import cn.hutool.http.useragent.Platform;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.HttpHeaders;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Locale;

/**
 * HttpUtil
 *
 * @author anle5
 * @since 2023/11/30 星期四 23:20
 */
public class HttpUtil {
    /**
     * 获取客户端ip
     *
     * @return 客户端ip
     */
    public static String getClientIp() {
        return JakartaServletUtil.getClientIP(getHttpServletRequest());
    }

    /**
     * 获取客户端设备信息
     *
     * @return platformName + version
     */
    public static String getClientPlatformName() {
        UserAgent clientUserAgent = getClientUserAgent();
        Platform platform = clientUserAgent.getPlatform();
        String name = platform.getName();
        String version = clientUserAgent.getVersion();
        return name + " " + version;
    }

    /**
     * 从ContextHolder的请求中获取 Locale
     *
     * @return Locale, 获取不到返回默认
     */
    public static Locale getLocale() {
        String acceptLanguage = getHttpServletRequest().getHeader(HttpHeaders.ACCEPT_LANGUAGE);
        return acceptLanguage == null ? Locale.getDefault() : Locale.forLanguageTag(acceptLanguage);
    }

    /**
     * 获取客户端UserAgent
     *
     * @return UserAgent
     */
    public static UserAgent getClientUserAgent() {
        return UserAgentUtil.parse(getHttpServletRequest().getHeader(Header.USER_AGENT.toString()));
    }

    /**
     * 获取 HttpServletRequest
     *
     * @return {@link HttpServletRequest}
     */
    public static HttpServletRequest getHttpServletRequest() {
        return getServletRequestAttributes().getRequest();
    }

    /**
     * 获取 ServletRequestAttributes
     *
     * @return {@link ServletRequestAttributes}
     */
    public static ServletRequestAttributes getServletRequestAttributes() {
        return (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    }
}
